{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# H-Field Probe Demo 1 (with CPA)\n",
    "\n",
    "This notebook is designed to work with an H-Field Probe. This can be used to attack devices without needing to modify them with a shunt resistor at all."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Normal Setup\n",
    "\n",
    "Perform a normal setup as you otherwise would. Adjust the platform & target as needed. Here we'll attack an XMEGA device on the CW308 UFO board for example. Note that because the UFO boards are missing the decoupling capacitors & have a resistive shunt, you may find they perform *worse* for H-Field probe usage than normal development kits.\n",
    "\n",
    "Neverless, we're going to give it a shot! We found the XMEGA works better than the STM32F3 target on the UFO board, so we'll do this tutorial with the XMEGA target board."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "SCOPETYPE = 'OPENADC'\n",
    "PLATFORM = 'CWLITEXMEGA'\n",
    "CRYPTO_TARGET = 'TINYAES128C'\n",
    "num_traces = 50\n",
    "CHECK_CORR = False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bash -s \"$PLATFORM\" \"$CRYPTO_TARGET\"\n",
    "cd ../../firmware/mcu/simpleserial-aes\n",
    "make PLATFORM=$1 CRYPTO_TARGET=$2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%run \"../Setup_Scripts/Setup_Generic.ipynb\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fw_path = '../../firmware/mcu/simpleserial-aes/simpleserial-aes-{}.hex'.format(PLATFORM)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cw.program_target(scope, prog, fw_path)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Adjustment for H-Field Probe\n",
    "\n",
    "Now time for the H-Field probe. We'll do the following:\n",
    "\n",
    "1. Attach LNA input to the H-Field probe.\n",
    "2. Attack LNA output to the ChipWhisperer measure input.\n",
    "3. Power up the LNA.\n",
    "4. Crank up the gain on the ChipWhisperer.\n",
    "\n",
    "Items 1-3 are done in this photo:\n",
    "\n",
    "<img src=\"img/hprobe_xmega_setup.jpg\" alt=\"SPA of Power Analysis\">\n",
    "\n",
    "Item 4 is done with the following line of code:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "scope.gain.gain = 70"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Visual Capture Loop\n",
    "\n",
    "Now adjusting the H-Field probe around, you can find an interesting location. The following loop will run up to 5000 captures, but throws them away. Just stop the loop if you find a good physical location (traces look stable). This might not be super-obvious: you'll see how to run a CPA attack next."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%run \"../Helper_Scripts/plot.ipynb\"\n",
    "plot = real_time_plot(plot_len=3000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tqdm import tnrange\n",
    "ktp = cw.ktp.Basic()\n",
    "\n",
    "key, text = ktp.next()\n",
    "\n",
    "for i in tnrange(5000, desc='Capturing traces'):    \n",
    "    trace = cw.capture_trace(scope, target, text, key)\n",
    "    if trace is None:\n",
    "        continue\n",
    "    plot.send(trace)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Actual Capture Loop & Analysis\n",
    "\n",
    "Then run the following two blocks - if the results aren't good, try another location!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import chipwhisperer as cw\n",
    "import chipwhisperer.analyzer as cwa\n",
    "\n",
    "project = cw.create_project(\"projects/hfield_demo.cwp\", overwrite = True)\n",
    "\n",
    "from tqdm import tnrange\n",
    "ktp = cw.ktp.Basic()\n",
    "\n",
    "for i in tnrange(250, desc='Capturing traces'):\n",
    "    key, text = ktp.next()  # manual creation of a key, text pair can be substituted here\n",
    "    trace = cw.capture_trace(scope, target, text, key)\n",
    "    if trace is None:\n",
    "        continue\n",
    "    project.traces.append(trace)\n",
    "    #send every 25th trace\n",
    "    if i % 25 == 0:\n",
    "        plot.send(trace)\n",
    "    \n",
    "project.save()\n",
    "\n",
    "attack = cwa.cpa(project, cwa.leakage_models.sbox_output)\n",
    "cb = cwa.get_jupyter_callback(attack)\n",
    "results = attack.run(cb, 25)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Next Steps & Cleanup\n",
    "\n",
    "You might notice that it's not super-obivuous how strong the signal is. Luckily there are better ways of getting quick feedback on leakage - in particular you can use the TVLA example code to plot in close-to-realtime a \"T-Test\", which will allow you to pinpoint leakage in a white-box scenario (i.e., you control the text & key).\n",
    "\n",
    "Hopefully this worked for you. Run the following to close the connection."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "scope.dis()\n",
    "target.dis()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
